//
//  UpdateUserInfoViewController.m
//  MobileShoppingMall
//
//  Created by 冯传昌 on 2021/4/23.
//  Copyright © 2021 冯传昌. All rights reserved.
//

#import "UpdateUserInfoViewController.h"

@interface UpdateUserInfoViewController ()<UIGestureRecognizerDelegate,UIImagePickerControllerDelegate,UITextFieldDelegate>

@property (nonatomic,strong) UIImageView *avatarImgV;

@property (nonatomic,strong) UIImageView *cameraImg;

@property (nonatomic,strong) UITextField *nickName_TF;

@property (nonatomic,strong) UIImagePickerController *imagePicker;

@property (nonatomic,copy) NSString *avatarUrlString;//头像

@end

@implementation UpdateUserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.topTitle = @"我的";
    self.view.backgroundColor = MainBackColor;
    
    [self initUI];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFieldEditChanged:)
              name:@"UITextFieldTextDidChangeNotification" object:self.nickName_TF];
}
-(void)textFieldEditChanged:(NSNotification *)obj{
    UITextField *textField = (UITextField *)obj.object;
    NSString *toBeString = textField.text;
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];       //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > 20) {
                textField.text = [toBeString substringToIndex:20];
            }
        }       // 有高亮选择的字符串，则暂不对文字进行统计和限制
        else{
        }
    }   // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况   else{
    if (toBeString.length > 20) {
        textField.text = [toBeString substringToIndex:20];
    }
}

#pragma mark - setter
- (void)setUserInfoDict:(NSDictionary *)userInfoDict{
    _userInfoDict = userInfoDict;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.avatarImgV sd_setImageWithURL:[NSURL URLWithString:[_userInfoDict[@"photo"] isEmpty] == YES ? @"":_userInfoDict[@"photo"]] placeholderImage:LoadImage(@"avatarBG")];
        self.avatarUrlString = [_userInfoDict[@"photo"] isEmpty]==NO ? _userInfoDict[@"photo"]:@"";
        self.nickName_TF.text = [_userInfoDict[@"name"] isEmpty]==NO ? _userInfoDict[@"name"]:@"";
    });
}
#pragma mark - UI
-(void)initUI{
    [self.view addSubview:self.avatarImgV];
    [self.avatarImgV addSubview:self.cameraImg];
    
    UILabel *leftLB = [[UILabel alloc] initWithFrame:CGRectMake(16, self.avatarImgV.bottom+45, 40, 22)];
    leftLB.font = FontSet(16);
    leftLB.textColor = MainBlackTextColor;
    leftLB.textAlignment = NSTextAlignmentLeft;
    leftLB.text = @"昵称";
    [self.view addSubview:leftLB];
    
    self.nickName_TF = [[UITextField alloc] initWithFrame:CGRectMake(leftLB.right + 20, leftLB.top-4, ScreenWidth-82, 30)];
    self.nickName_TF.textColor = MainGrayTextColor;
    self.nickName_TF.font = FontSet(16);
    self.nickName_TF.placeholder = @"请输入您的昵称！";
    self.nickName_TF.delegate = self;
    [self.view addSubview:self.nickName_TF];
    
    UIView *lineV = [[UIView alloc] initWithFrame:CGRectMake(16, self.nickName_TF.bottom+15, ScreenWidth-32, 1)];
    lineV.backgroundColor = RGBA(0, 0, 0, 0.1f);
    [self.view addSubview:lineV];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(30, ScreenHeight-kSafe_Bottom-100, ScreenWidth-60, 40);
    btn.backgroundColor = RGB(26, 128, 255);
    btn.clipsToBounds = YES;
    btn.layer.cornerRadius = 20;
    [btn.titleLabel setFont:FontSet(18)];
    [btn setTitle:@"确定修改" forState:normal];
    [btn setTitleColor:UIColor.whiteColor forState:normal];
    [btn addTarget:self action:@selector(updateClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}
#pragma mark - lazy
- (UIImageView *)avatarImgV{
    if (!_avatarImgV) {
        _avatarImgV = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenWidth/2-40, self.topNavView.bottom + 35, 80, 80)];
        _avatarImgV.clipsToBounds = YES;
        _avatarImgV.layer.cornerRadius = 40;
        _avatarImgV.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
        tap.delegate = self;
        [_avatarImgV addGestureRecognizer:tap];
    }
    return _avatarImgV;
}
- (UIImageView *)cameraImg{
    if (!_cameraImg) {
        _cameraImg = [[UIImageView alloc] initWithFrame:CGRectMake(30, 32, 19, 15)];
        _cameraImg.image = LoadImage(@"个人中心_camera");
        _cameraImg.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
        tap.delegate = self;
        [_cameraImg addGestureRecognizer:tap];
    }
    return _cameraImg;
}
#pragma mark - SEL
-(void)tapClick:(UIGestureRecognizer *)tap{
    //选择图片 或 打开相机
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"更换头像" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *photosAction = [UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self selectUserAvatarWithType:0];
    }];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"相机拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self selectUserAvatarWithType:1];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:nil];
    [alert addAction:photosAction];
    [alert addAction:cameraAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}
///选择用户头像
-(void)selectUserAvatarWithType:(NSInteger)type{
    self.imagePicker = [[UIImagePickerController alloc] init];
    self.imagePicker.delegate = self;
    self.imagePicker.allowsEditing = YES;
    if (type == 0) {
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }else{
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}
//获取选择的图片
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    self.avatarImgV.image = image;
    [NetWorkingGeneral uploadImageWithImage:image withSuceessBlock:^(id  _Nonnull responseObj) {
        NSString *imgUrl = (NSString *)responseObj;
        [self.avatarImgV sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:LoadImage(@"avatarBG")];
        self.avatarUrlString = imgUrl;
    }];
}
//从相机或者相册界面弹出
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}
//修改个人信息
-(void)updateClick{
    if ([self.nickName_TF.text isEmpty] == YES) {
        [[XNProgressHUD shared] showWithTitle:@"请输入您的昵称！"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[XNProgressHUD shared] dismiss];
        });
        return;
    }
    [NetWorkingPerson updateUserInfoWithAvatarImg:self.avatarUrlString withName:self.nickName_TF.text withSuccessBlock:^(id  _Nonnull responseObj) {
        if ([responseObj[@"code"] intValue] == 200) {
            [[XNProgressHUD shared] showSuccessWithTitle:@"修改成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[XNProgressHUD shared] dismiss];
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    }];
}

@end


